package com.unlcn.ils.wms.backend.service.bigscreen.impl;

import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.domain.ResultDTOWithPagination;
import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.unlcn.ils.wms.backend.bo.biBO.BiFrontProgressBO;
import com.unlcn.ils.wms.backend.enums.TmsUrlEnum;
import com.unlcn.ils.wms.backend.enums.TmsUrlTypeEnum;
import com.unlcn.ils.wms.backend.enums.WmsFrontOnWayStatusEnum;
import com.unlcn.ils.wms.backend.service.bigscreen.FrontOnWayService;
import com.unlcn.ils.wms.base.dto.WmsOnWayLineDTO;
import com.unlcn.ils.wms.base.mapper.bigscreen.BiFrontOnWayMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.BiFrontOnWayExtMapper;
import com.unlcn.ils.wms.base.mapper.sys.TmsCallHistoryMapper;
import com.unlcn.ils.wms.base.model.bigscreen.BiFrontOnWay;
import com.unlcn.ils.wms.base.model.sys.TmsCallHistory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 前端在途统计service
 */
@Service
public class FrontOnWayServiceImpl implements FrontOnWayService {

    @Autowired
    private BiFrontOnWayExtMapper biFrontOnWayExtMapper;

    @Autowired
    private BiFrontOnWayMapper biFrontOnWayMapper;

    @Autowired
    private TmsCallHistoryMapper tmsCallHistoryMapper;

    @Value("${tms.pickup.host.url}")
    private String propertyUrl;

    @Value("${tms.pickup.host.timeout}")
    private String propertyTime;

    @Value("${tms.encode.key}")
    private String propertyKey;

    private Logger LOGGER = LoggerFactory.getLogger(FrontOnWayServiceImpl.class);

    @Override
    public List<BiFrontOnWay> onWayLine() {
        return biFrontOnWayExtMapper.onWayLine();
    }

    @Override
    public void addFrontOnWay() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String dateStr = format.format(calendar.getTime());


        String strUrl = propertyUrl + TmsUrlEnum.BI_FOREPROGRESS.getText();
        Integer time = Integer.parseInt(propertyTime);
        String encode_key = propertyKey;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("encode-key", encode_key);

        String result = null;

        TmsCallHistory tmsCallHistory = new TmsCallHistory();

        try {

            tmsCallHistory.setTmsUrl(strUrl);
            tmsCallHistory.setPullOrPush(0);
            tmsCallHistory.setCallStartTime(new Date());
            tmsCallHistory.setTmsUrlType(TmsUrlTypeEnum.BI_FOREPROGRESS.getValue());
            tmsCallHistory.setParameters(dateStr);

            result = HttpRequestUtil.sendHttpPost(strUrl, headerMap, map, time);

        } catch (Exception e) {
            LOGGER.error("FrontOnWayServiceImpl.addFrontOnWay error : ", e);
            throw new BusinessException("访问tms接口失败");
        }

        try {
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String msg = jsonObject.getString("message");
                String records = jsonObject.getString("records");
                Boolean success = jsonObject.getBoolean("success");

                tmsCallHistory.setCallEndTime(new Date());
                tmsCallHistory.setMessage(msg);
                tmsCallHistory.setResultContent(result);

                if (!success) {
                    LOGGER.error("FrontOnWayServiceImpl callTms error msg: {}", msg);
                    tmsCallHistory.setResultCount(0);
                    tmsCallHistory.setSuccess(success);
                    tmsCallHistoryMapper.insertSelective(tmsCallHistory);
                }

                List<BiFrontProgressBO> tmsBOList = JSONArray.parseArray(records, BiFrontProgressBO.class);
                tmsCallHistory.setResultCount(tmsBOList.size());
                tmsCallHistory.setSuccess(success);
                tmsCallHistoryMapper.insertSelective(tmsCallHistory);

                SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmSS");
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(new Date());
                String dateStr2 = format2.format(calendar2.getTime());

                tmsBOList.forEach((BiFrontProgressBO v) -> {
                    //新增
                    BiFrontOnWay biFrontOnWay = new BiFrontOnWay();
                    biFrontOnWay.setDispatchNo(v.getShipno());
                    biFrontOnWay.setOrderCount(Integer.parseInt(Strings.isNullOrEmpty(v.getQty()) ? "0" : v.getQty()));
                    biFrontOnWay.setTransModel(v.getTransmode());
                    biFrontOnWay.setStartPlace(v.getRoute_start());
                    biFrontOnWay.setEndPlace(v.getRoute_end());
                    biFrontOnWay.setSpeed(new BigDecimal(Strings.isNullOrEmpty(v.getProgress()) ? "0" : v.getProgress()));
                    biFrontOnWay.setVoverdue(v.getExceed_status());
                    biFrontOnWay.setVersion(dateStr2);
                    biFrontOnWay.setEstArrivalDate(v.getEst_arrival_date());
                    biFrontOnWay.setAssignDate(v.getAssign_date());
                    biFrontOnWay.setOutDate(v.getOut_date());
                    biFrontOnWayMapper.insertSelective(biFrontOnWay);

                });
            }

        } catch (Exception e) {
            LOGGER.error("PickDataServiceImpl.addPickData error : ", e);
            throw new BusinessException("保存失败");
        }
    }

    /**
     * 2017-12-19 <p>新需求:百分比完成的不用显示，
     * 设置一个查询条件（状态查询），超期水铁运输10天以内数据，陆运4天以内，
     * 一页显示10条，数据10秒内自动滚动，运输模式更改为图标。进度表未完成百分百全部显示，异常未完成都显示。</p>
     *
     * @param dto
     * @return
     */

    @Override
    public ResultDTOWithPagination<List<BiFrontOnWay>> onWayLineWithPagiation(WmsOnWayLineDTO dto) throws Exception {
        LOGGER.info("FrontOnWayServiceImpl.onWayLineWithPagiation param dto :{} ", dto);
        if (Objects.equals(dto, null))
            throw new BusinessException("传入参数不能为空!");
        if (dto.getPageNo() < 0)
            dto.setPageNo(1);
        ResultDTOWithPagination<List<BiFrontOnWay>> result = new ResultDTOWithPagination<>();
        HashMap<String, Object> paramMap = Maps.newHashMap();
        //默认显示未完成数据
        paramMap.put("status", StringUtils.isBlank(dto.getStatus()) ? WmsFrontOnWayStatusEnum.NOT_FINISHED.getCode() : dto.getStatus());
        //如果查询条件不为空
        paramMap.put("orderBy", StringUtils.isBlank(dto.getOrder()) ? "create_time desc" : dto.getOrder());
        paramMap.put("start", dto.getStartIndex());
        paramMap.put("limitEnd", dto.getPageSize());
        List<BiFrontOnWay> biFrontOnWays = biFrontOnWayExtMapper.selectOnWayLineByParam(paramMap);
        int count = biFrontOnWayExtMapper.selectCountOnWayLineByParam(paramMap);
        PageVo pageVo = new PageVo();
        pageVo.setPageSize(dto.getPageSize());
        pageVo.setPageNo(dto.getPageNo());
        pageVo.setOrder(dto.getOrder());
        pageVo.setTotalRecord(count);
        result.setData(biFrontOnWays);
        result.setPageVo(pageVo);
        return result;
    }
}
